import { getInfoRequest } from '@/api/seo.js'

const seo = {
  namespaced: true,
  state: {
    info: null
  },

  getters: {},

  mutations: {
    SET_INFO: (state, info) => {
      state.info = info
    },


    SET_DOCUMENT_TITLE: (state, title) => {
      if (title) document.title = title
    },


    SET_DOCUMENT_KEYWORDS: (state, keywords) => {
      if (keywords) document.querySelector('meta[name="Keywords"]').setAttribute('content', keywords)
    },

    SET_DOCUMENT_DESCRIPTION: (state, description) => {
      if (description) document.querySelector('meta[name="Description"]').setAttribute('content', description)
    }

  },

  actions: {
    getInfoAction({ commit }, parameters) {
      return new Promise((resolve, reject) => {
        getInfoRequest(parameters)
          .then(response => {
            console.log('\n\n' + 'set global seo' + '\n\n');
            const seo = response.result
            commit('SET_INFO', seo)
            if (seo) {
              commit('SET_DOCUMENT_KEYWORDS', seo.keywords)
              commit('SET_DOCUMENT_DESCRIPTION', seo.description)
            }

            resolve(seo)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    setUpSeo({ commit, dispatch }, parameters) {
      return new Promise((resolve, reject) => {
        dispatch("getInfoAction", parameters).then(() => resolve).catch((error) => reject())
      });
    }
  }
}

export default seo
